package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.SiteMapper;
import com.indusfo.spc.mapper.SiteMatMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.Area;
import com.indusfo.spc.pojo.Datadict;
import com.indusfo.spc.pojo.Site;
import com.indusfo.spc.service.SiteService;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class SiteServiceImpl implements SiteService {

    private  static  final Logger logger = LoggerFactory.getLogger(SiteServiceImpl.class);

    @Resource
    private UploadMapper uploadMapper;
    @Resource
    private SiteMapper siteMapper;
    @Resource
    private SiteMatMapper siteMatMapper;

    @Override
    public JSONObject selectSite(Site site) {
        List<Site> siteList = null;
        int count = 0;
        try {
            Integer pagesize = site.getPagesize();
            Integer pageindex = site.getPageindex();
            if(pagesize != null && pageindex != null) {
                site.setIncept(pagesize*(pageindex - 1));
            }
            siteList = siteMapper.selectSite(site);
            //查询分页总记录数
            count = siteMapper.countSite(site); //返回查询到的总记录数
            if (siteList.isEmpty()) {
                return JSONObject.oK("没有查询到相关数据", siteList, count);
            }
            return JSONObject.oK("查询成功", siteList, count);
        } catch (
                GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject insertSite(Site site) {
        try {
            if(site.getSiteId()!= null) {
                throw new ParamsErrorException("新增时，不能填写id");
            }
            checkParam(site);
            // 调用存储过程
            int row = siteMapper.insertSelective(site);
            if(row == 0) {
                throw new ModifyFailedException("数据新增失败");
            }
            return JSONObject.oK("新增成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject updateSite(Site site) {
        try {
            if(site.getSiteId()== null) {
                throw new ParamsErrorException("请选择要编辑的库位");
            }
            checkParam(site);
            // 调用存储过程
            int row = siteMapper.updateByPrimaryKeySelective(site);
            if(row == 0) {
                throw new ModifyFailedException("数据编辑失败");
            }
            return JSONObject.oK("编辑成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject definedSite(Long[] siteIds, Integer dataState) {
        try {
            if(dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if(dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (siteIds == null) {
                throw new ParamsErrorException("库位id不能为空");
            }
            if(dataState == 2){
                for(Long siteId : siteIds ) {
                    int row = siteMatMapper.deleteBySiteId(siteId.intValue());
                }
            }
            // 执行存储过程
            int row = siteMapper.definedSite(siteIds, dataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public String checkNoRepeatExcel(Site site) {

        //区域名称
        String areaName = site.getAreaName();
        //库位编码
        String siteCode = site.getSiteCode();
        //库位名称
        String siteName = site.getSiteName();
        //库位类型名称
        String siteTypeName = site.getSiteTypeName();
        if(StringUtils.isEmpty(areaName) && StringUtils.isEmpty(siteCode) && StringUtils.isEmpty(siteTypeName) && StringUtils.isEmpty(siteName)){
            return "该行数据为空/不存在";
        }
        if(StringUtils.isEmpty(areaName)){
            return "区域名称为空";
        }
        Map<String, Area> areaMap = uploadMapper.queryArea();
        if(!areaMap.containsKey(areaName)){
            return "区域名称填写错误/不规范";
        }
        site.setAreaId(areaMap.get(areaName).getAreaId());
        if (StringUtils.isEmpty(site.getSiteCode())) {
            return "库位编码为空";
        }
        if (site.getSiteCode().getBytes().length > 50) {
            return "库位编码超过规定,长度50字节,25个汉字";
        }
        if (StringUtils.isEmpty(site.getSiteName())) {
            return "请填写库位名称";
        }
        if(StringUtils.isEmpty(siteTypeName)){
            return "库位类型名称为空";
        }
        Map<String, Datadict> siteTypeMap = uploadMapper.queryType(101044);
        if(!siteTypeMap.containsKey(siteTypeName)){
            return "库位类型名称填写不规范";
        }
        site.setSiteTypeId(siteTypeMap.get(siteTypeName).getItemId());
        if (site.getSiteName().getBytes().length > 50) {
            return "库位名称超过规定,长度50字节,25个汉字";
        }
        // 编码不能重复
        Integer depCounts = siteMapper.querySite(site);
        if (depCounts !=0) {
            return "库位编码已存在";
        }
        // 名称不能重复
        Integer siteCounts = siteMapper.querySiteName(site);
        if (siteCounts !=0) {
            return "名称已存在";
        }
        return null;
    }

    @Override
    public JSONObject updateListSite(List<Site> siteList) {
        uploadMapper.updateListSite(siteList);
        return null;
    }

    /**
     * 参数校验
     */
    private void checkParam(Site site) {
        if (site.getAreaId() == null) {
            throw new ParamsErrorException("请选择区域");
        }
        if (StringUtils.isEmpty(site.getSiteCode())) {
            throw new ParamsErrorException("请填写库位编码");
        }
        if (site.getSiteCode().getBytes().length > 50) {
            throw new ParamsErrorException("库位编码超过规定,长度50");
        }
        if (StringUtils.isEmpty(site.getSiteName())) {
            throw new ParamsErrorException("请填写库位名称");
        }
        if (site.getSiteName().getBytes().length > 50) {
            throw new ParamsErrorException("库位名称超过规定,长度50");
        }
        if (site.getSiteTypeId() == null) {
            throw new ParamsErrorException("请库位类型");
        }
        // 编码不能重复
        Integer depCounts = siteMapper.querySite(site);
        if (depCounts !=0) {
            throw new ParamsErrorException("该库位编码已存在");
        }
        // 名称不能重复
        Integer siteCounts = siteMapper.querySiteName(site);
        if (siteCounts !=0) {
            throw new ParamsErrorException("该库位名称已存在");
        }
    }

}
